package Internect;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MemberManager {
    // 添加会员
    public boolean addMember(String name, String password, String email) {
        try {
            // 检查会员是否已存在
            File file = new File("member_info.txt");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;

            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts[0].equals(name)) {
                    reader.close();
                    return false;
                }
            }

            reader.close();

            // 添加会员信息
            FileWriter writer = new FileWriter(file, true);
            writer.write(name + "," + password + "," + email + "\n");
            writer.close();

            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    // 删除会员
    public boolean deleteMember(String name) {
        try {
            // 读取会员信息文件
            File file = new File("member_info.txt");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;
            List<String> lines = new ArrayList<String>();

            // 删除对应的会员信息
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (!parts[0].equals(name)) {
                    lines.add(line);
                }
            }

            reader.close();

            // 重新写入会员信息文件
            FileWriter writer = new FileWriter(file);
            for (String l : lines) {
                writer.write(l + "\n");
            }
            writer.close();

            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    // 修改会员信息
    public boolean modifyMember(String name, String password, String email) {
        try {
            // 读取会员信息文件
            File file = new File("member_info.txt");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = null;
            List<String> lines = new ArrayList<String>();

            // 修改对应的会员信息
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts[0].equals(name)) {
                    lines.add(name + "," + password + "," + email);
                } else {
                    lines.add(line);
                }
            }

            reader.close();

            // 重新写入会员信息文件
            FileWriter writer = new FileWriter(file);
            for (String l : lines) {
                writer.write(l + "\n");
            }
            writer.close();

            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
